from pattern.circuit import Control
import re

class entry(Control):

    MULTIPART = re.compile('Content-Disposition: form-data; name="(.*)"\r\n([^\0]*)', re.MULTILINE)

    def incoming(self, event):
        ct = event.trail.headers["content-type"]
        cl = int(event.trail.headers["content-length"])
        request = event.trail.rfile.read(cl)
        bridge = self.acquireInterface(event, "request")
        if bridge is not None:
            if ct.startswith("multipart/form-data"):
                self.multipart(request, bridge)
            else:
                self.singlepart(request, bridge)
        # Send OK
        bridge = self.acquireInterface(event, "page")
        if bridge is not None:
            bridge.push()
        else:
            self._sendOK(event)
            
    def _sendOK(self, event):
        page = "OK"
        event.trail.send_response(200)
        event.trail.send_header("Content-type", "text/plain")
        event.trail.send_header("Content-Length", str(len(page)))
        event.trail.end_headers()
        event.trail.wfile.write(page)
    
    def multipart(self, request, bridge):
        delimiter = request.split("\r\n",1)[0] #@@@
        for part in request.split(delimiter):
            mo = self.MULTIPART.match(part.strip())
            if mo:
                name = mo.group(1)
                value = mo.group(2)
                bridge.push(name + "=" + value)
            
    def singlepart(self, request, bridge):
        bridge.push(request)
